
import { getToken, setToken, removeToken, setRoles, getRoles, removeRoles, setName, getName, removeName } from '@/utils/auth'


const user = {
    state: {
        user: '',
        status: '',
        code: '',
        token: getToken(),
        name: '',
        avatar: '',
        introduction: '',
        roles: [],
        setting: {
            articlePlatform: []
        },
        languse: 'zh'
    },
    mutations: {
        SET_CODE: (state, code) => {
            state.code = code
        },
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_INTRODUCTION: (state, introduction) => {
            state.introduction = introduction
        },
        SET_SETTING: (state, setting) => {
            state.setting = setting
        },
        SET_STATUS: (state, status) => {
            state.status = status
        },
        SET_NAME: (state, name) => {
            state.name = name
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles
        }
    },

    actions: {
        // 用户名登录
        login ({ commit }, userInfo) {
            return new Promise((resolve, reject) => {
                this._vm.api.login(userInfo).then(response => {
                    const data = response.data
                    commit('SET_TOKEN', data.token)
                    setToken(response.data.token)
                    setRoles(data.group)
                    setName(userInfo.name)
                    resolve(response)
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 获取用户信息
        GetUserInfo ({ commit }) {
            return new Promise((resolve) => {  //正常情况下,是通过接口获取用户信息
                commit('SET_ROLES', getRoles())
                commit('SET_NAME', getName())
                resolve()
            })
        },


        // 登出
        LogOut ({ commit }) {
            return new Promise((resolve) => {
                commit('SET_TOKEN', '')
                commit('SET_ROLES', [])
                removeToken()
                removeRoles()
                removeName()
                resolve()
            })
        },
        // 动态修改权限
        ChangeRoles ({ dispatch }, role) {
            return new Promise(resolve => {
                setRoles(role)
                dispatch('GenerateRoutes', role)
                resolve()
            })
        }
    }
}

export default user
